<?php


namespace app\tickets\controller;


use app\common\controller\Common;
use app\index\controller\Base;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Hairpin extends Base
{

    /**
     * 票类型
     * 发卡规则列表
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function index(){
        $common = new Common();
        //状态
        $batch = $common->publicAttribute("batch");
        $this->assign("batch",$batch);

        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        if(!empty($_GET['keyword'])){
            $where['title'] = ['like',"%".$_GET['keyword']."%"];
        }
        if(!empty($_GET['status'])){
            $where['status'] = $_GET['status'];
        }
        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $publicTable = "tickets_hairpin";
                $newSql = $common->public_select($publicTable,$where,null,$start,$limit);
                $list = $newSql->order("id desc")->select();
                foreach ($list as $k=>$v){
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);

                    if($v['type']==2){
                        $list[$k]['hairpintime'] = "--";
                    }else{
                        $list[$k]['hairpintime'] = empty($v['hairpintime'])?"未发卡":$v['hairpintime'];
                    }
                    $list[$k]['status_name'] = $batch[$v['status']];
                    $list[$k]['type_name'] = ($v['type']==1)?"纸质票":"电子票";
                }
                $count = $common->public_select($publicTable,$where)->count("*");
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }
        return $this->fetch('index');
    }

    /**
     * 添加规则视图
     * @return mixed|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function addHairpin(){
        //票类型
        $common = new Common();
        $tickets_type = $common->publicAttribute("tickets_type");
        $this->assign("tickets_type",$tickets_type);
        $enable_status = $common->publicAttribute("batch");
        $this->assign("batch",$enable_status);
        if(empty($_GET['id'])){
            return view("create");
        }else{
            //获取批次详细信息
            $publicTable = "tickets_hairpin";
            $where['id'] = $_GET['id'];
            $newSql = $common->public_select($publicTable,$where);
            $detail = $newSql->find();
            $this->assign("detail",$detail);
            return $this->fetch('update');
        }
    }

    /**
     * 执行添加
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function doHairpin(){
        $common = new Common();
        Db::startTrans();
        try{
            $rule = [
                ["sina", "require", "批次校验不能为空"],
                ["count", "require", "发布数量不能为空"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();
            $thisWechat = Session::get("thisWechat");
            $value['uniacid'] = $thisWechat['id'];
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }

            if(strlen($value['sina'])!=6){
                throw new Exception("批次校验的长度必须为6位");
            }

            if($value['count']>50000){
                throw new Exception("发布数最大为5万");
            }


            $table = "tickets_hairpin";
            $tableWhere['sina'] = $value['sina'];
            $hairpinId = $common->public_select($table,$tableWhere)->value("id");
            if(!empty($hairpinId)){
                throw new Exception("该批次号已存在，请勿重复添加");
            }


            $id = $common->handle($table,$value);
            if(!empty($value['id'])){
                $log['remark'] = "用户【" . Session::get("user_name") . "】更新批次规则,关联id【".$id."】";
            }else{
                $log['remark'] = "用户【" . Session::get("user_name") . "】添加批次规则,关联id【".$id."】";
            }
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "添加成功";
            Db::commit();
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }


    public function cancellation(){
        $common = new Common();
        Db::startTrans();
        try{
            $rule = [
                ["id", "require", "非法操作"],
                ["status", "require", "非法操作"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }
            $table = "tickets_hairpin";
            $where['id'] = $value['id'];
            $detail = $common->public_select($table,$where)->find();
            $log['remark'] = "用户【" . Session::get("user_name") . "】操作规则状态，将该批次票设为作废状态,发卡规则id【".$value['id']."】";
            $common->addLog($log);

            $tickets_card = "tickets_card";
            $where1['hairpin_id'] = $detail['id'];
            $common->public_select($tickets_card,$where1)->update(['status'=>$value['status']]);

            $common->handle($table,$value);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            Db::commit();
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    /**
     * YQ20210129随机数MD5前6
     * 发卡操作
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function hairpinApi(){
        $common = new Common();
        Db::startTrans();
        try{
            $rule = [
                ["id", "require", "非法操作"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }
            $table = "tickets_hairpin";
            $detail = $common->public_select($table,$value)->find();
            $log['remark'] = "用户【" . Session::get("user_name") . "】执行发卡操作,发卡规则id【".$value['id']."】";
            $common->addLog($log);
            if($detail['hairpintime']!=0){
                throw new Exception("改规则已使用，请勿重复发卡");
            }
            /*$tense = date("H");
            if($tense>8 & $tense<18){
                throw new Exception("请勿在检票时间内操作,禁止操作时间8:00 - 18:00");
            }*/
            $count = $detail['count'];
            $tickets_card = "tickets_card";
            for ($i=1;$i<=$count;$i++){
                $no = $detail['sina'].date("d");
                $token = sprintf("%06d", $i);
                $no = $no.$token;
                $showmd5 = md5($no);
                $showmd5 = substr($showmd5, 0,6);
                $no = $no.$showmd5;
                $data['uniacid'] = $detail['uniacid'];
                $data['hairpin_id'] = $detail['id'];
                $data['no'] = $no;
                $data['status'] = $detail['status'];
                $data['addtime'] = time();
                $data['add_id'] = Session::get("id");
                $common->handle($tickets_card,$data);
            }
            //更新发卡时间
            $value['hairpintime'] = date("Y-m-d H:i:s",time());
            $common->handle($table,$value);
            $black['code'] = 0;
            $black['msg'] = "发卡成功";
            Db::commit();
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    function newtext($params){
        $myfile = fopen(__DIR__."/newfile.txt", "a") or die("Unable to open file!");//这个是在c盘根目录生成文件
        $txt = $params;//获取参数
        $b="";
        foreach($txt as $k=>$v){
            $b = $b ."[".$k."]=>".$v."\n";
        }
        fwrite($myfile, $b);//写入内容,可以写多次哦,不过没啥意义,因为你拼接好字符串,一次写入就行了
        fclose($myfile);//关闭该操作
    }


    /**
     * 生成加密算法
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function createtoken(){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < 32; $i++){
            $str .= $chars[mt_rand(0, $lc)].rand(1000000, 9999999);
        }
        return $str;
    }


    /**
     * 查看发卡明细
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function detail(){
        $common = new Common();
        $batch = $common->publicAttribute("batch");
        $this->assign("batch",$batch);

        //状态
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];

        if(!empty($_GET['hairpin_id'])){
            $hairpin_id =  $where['hairpin_id'] = $_GET['hairpin_id'];
        }
        $this->assign("hairpin_id",$hairpin_id);

        if(!empty($_GET['keyword'])){
            $where['no'] = ['like',"%".$_GET['keyword']."%"];
        }
        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];

                if(empty($_GET['pageSize'])){
                    $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                }else{
                    $limit = empty($_GET['pageSize']) ? 10 : $_GET['pageSize'];
                }

                $start = ($page - 1) * $limit;
                $list = Db::name("tickets_card")->where($where)->limit($start,$limit)->order("id desc")->select();
                foreach ($list as $k=>$v){
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                    $list[$k]['effectivetime'] = empty($v['effectivetime'])?"未生效":date("Y-m-d H:i:s",$v['effectivetime']);
                    $list[$k]['status'] = $batch[$v['status']];
                }
                $count = Db::name("tickets_card")->where($where)->count("*");
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }
        return $this->fetch('detail');
    }


    /**
     * 导出票种
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function export(){
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        $where['hairpin_id'] = $_POST['hairpin_id'];

        $sina = Db::name("tickets_hairpin")->where(['id'=>$_POST['hairpin_id']])->value("sina");

        $lists = Db::name("tickets_card")->where($where)->field("id,no")->order("id asc")->select();
        require ROOT_PATH."extend/PHPExce/PHPExcel.php";//引入PHPExcel加载文件
        $objPHPExcel=new \PHPExcel();
        $objPHPExcel->getProperties()->setCreator('http://www.jb51.net')
            ->setLastModifiedBy('http://www.jb51.net')
            ->setTitle('Office 2007 XLSX Document')
            ->setSubject('Office 2007 XLSX Document')
            ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
            ->setKeywords('office 2007 openxml php')
            ->setCategory('Result file');
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1','ID')
            ->setCellValue('B1','编号');
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);#设置单元格宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(38);
        $i=2;
        foreach ($lists as $k=>$v){
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$i,$v['id'])
                ->setCellValue('B'.$i,$v['no']);
            $i++;
        }

        $objPHPExcel->getActiveSheet()->setTitle('用户信息');
        $objPHPExcel->setActiveSheetIndex(0);
        //$filename=urlencode('订单数据').'_'.date('Y-m-dHis');
        $filename='门票列表'.'_'.$sina;

        //*生成xlsx文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter=\PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');

        $objWriter->save('php://output');

        $xlsData = ob_get_contents();
        ob_end_clean();

        $return = ['filename' => $filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)];

        return $return;
        exit;
    }


}